import {Server as WebSocketServer} from 'rpc-websockets'
import  {JSJaCConsoleLogger}  from '../jsjac'
import { SoaUtil } from '../soa'
/**
 * 启动rpcServer
 */
export class RpcServer {
    private static server:WebSocketServer
    private static log=new JSJaCConsoleLogger()

    /**
     * 启动rpcServer
     * @param port 启动websocket的服务器商品
     */
    public static startRpcServer(port:number):void{
        this.server=new WebSocketServer({
            host:'localhost',
            port:port
        })
        this.log.info('rpcServer is start at:'+port)
        const soaRpcMehtods=SoaUtil.getRegisterRpcMethod()
        soaRpcMehtods.forEach(rpcMethod=>{
            this.log.info('register rpcMethod:'+rpcMethod.methodName)
            if(!rpcMethod.isPublic){
               this.server.register(rpcMethod.methodName,rpcMethod.handle).protected()
            } else {
               this.server.register(rpcMethod.methodName,rpcMethod.handle).public()
            }
        })

    }
    /**
     * 关闭rpcServer
     */
    public static close(){
        if(this.server){
            console.info(' call close ws Server')
            this.server.close()
        }
    }
}